package com.hippy.erya.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hippy.erya.base.auth.context.LoginContextHolder;
import com.hippy.erya.common.DateUtil;
import com.hippy.erya.entity.BaseDO;
import com.hippy.erya.sys.core.constant.cache.Cache;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

public class BaseQueryWrapper<T> {

    public static <T> void buildQuery(QueryWrapper<T> queryWrapper, String timeRage, String column) {
        if (StringUtils.isEmpty(timeRage)) {
            return;
        }
        String[] purchaseTimeArray = timeRage.split("-");
        if (purchaseTimeArray.length != 2) {
            return;
        }
        Date startDate = DateUtil.parse(purchaseTimeArray[0].trim(), DateUtil.SLASH_PATTERN);
        Date endDate = DateUtil.parse(purchaseTimeArray[1].trim(), DateUtil.SLASH_PATTERN);
        queryWrapper.ge(column, startDate);
        queryWrapper.le(column, endDate);
    }

    public static <T> T buildQuery() {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USABLE_FLAG", Cache.USABLE);
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("USER_CODE", LoginContextHolder.getContext().getUser().getId());
        return (T) queryWrapper;
    }

    public static <T> void outputMessage(T tableDo) {
        String shopName = LoginContextHolder.getContext().getUser().getShopName();
        if (tableDo instanceof BaseDO) {
            ((BaseDO) tableDo).setCreatedBy(shopName);
            ((BaseDO) tableDo).setUpdatedBy(shopName);
        }
    }

}
